package dyy.zc.alumnibook.utils;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import dyy.zc.alumnibook.R;
import dyy.zc.alumnibook.application.MyApplication;
import dyy.zc.alumnibook.bean.Friend;
import dyy.zc.alumnibook.bean.FriendCircle;
import dyy.zc.alumnibook.bean.PhotoAlbum;
import dyy.zc.alumnibook.bean.UserInfo;
import dyy.zc.alumnibook.constant.Constants;
import dyy.zc.alumnibook.ui.activity.ChangeInfoActivity;
import dyy.zc.alumnibook.ui.activity.EditInfoActivity;
import dyy.zc.alumnibook.ui.activity.FriendHomePageActivity;
import dyy.zc.alumnibook.ui.activity.LoginActivity;
import dyy.zc.alumnibook.ui.activity.MainActivity;
import dyy.zc.alumnibook.ui.activity.PublishActivity;
import dyy.zc.alumnibook.ui.activity.RegisterActivity;

/**
 * Created by chuan on 2017/4/11.
 */

public class BmobUtils {
    public static boolean loginSuccess = false;
    private Context context;
    private boolean registerSuccess = true;
    /**
     * 添加朋友
     */
    private boolean cun = false;
    private UserInfo userInfo;
    public BmobUtils(Context context){
        this.context = context;
    }

    /**
     * 登录查询是否账号密码输入错误
     */
    public void queryAccount(final UserInfo account) {
        BmobQuery<UserInfo> bmobQuery = new BmobQuery<>();
        bmobQuery.findObjects(new FindListener<UserInfo>() {
            @Override
            public void done(List<UserInfo> list, BmobException e) {
                if (e == null) {
                    Log.e("queryAccount", "ok");
                    for (UserInfo a :
                            list) {
                        if (a.getAccount().equals(account.getAccount()) && a.getPassword().equals(account.getPassword())) {
                            loginSuccess = true;
                            MyApplication.getInstance().saveUserInfo(a);
                            break;
                        }
                    }
                } else {
                    e.printStackTrace();
                    Log.e("queryAccount", "Failed");
                }
                ((LoginActivity) context).handler.sendEmptyMessage(Constants.ResultCode.RESULT_SUCCESS);
            }
        });
    }

    /**
 * 找回密码
 */
    public void getBackYourAccount(final String phone, final String userPassword){
        final BmobQuery<UserInfo> query = new BmobQuery<>();
        query.findObjects(new FindListener<UserInfo>() {
            @Override
            public void done(List<UserInfo> list, BmobException e) {
                if (e == null){
                    Log.e("getBackYourAccount", "ok");
                    for (UserInfo a :
                            list) {
                        if (a.getAccount().equals(phone)){
                            a.setPassword(userPassword);
                            findPassword(a);
                            break;
                        }
                    }
                }else {
                    Log.e("getBackYourAccount", e.getMessage());
                }
            }
        });
    }

    /**
     * 更新用户密码
     *
     * @param account
     */
    public void findPassword(UserInfo account) {
        account.update(account.getId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("updateAccountInfo", "ok");
                    ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                } else {
                    e.printStackTrace();
                    Log.e("updateAccountInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 上传图片文件--注册时默认的用户头像
     *
     * @param bmobFile
     * @param account
     */
    public void upMoRenFile(final BmobFile bmobFile, final UserInfo account) {
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    account.setHead(bmobFile);
                    addUserInfo(account);
                    Log.e("upLoadFile", "ok--" + bmobFile.getFileUrl());
                } else {
                    e.printStackTrace();
                    Log.e("upLoadFile", e.getMessage());
                }
            }
        });
    }

    /**
     * 增加用户
     * @param account
     */
    public void addUserInfo(final UserInfo account) {
        account.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null){
                    ((RegisterActivity) context).account.setId(s);
                    updateInfo(((RegisterActivity) context).account);
                    ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                }else {
                    Log.e("Bmob-updateInfoFailed", e.getMessage());
                }
            }
        });
    }

    /**
     * 注册新用户验证
     * @param userPhone 账号
     */
    public void registerChecked(final String userPhone) {
        BmobQuery<UserInfo> query = new BmobQuery<>();
        query.findObjects(new FindListener<UserInfo>() {
            @Override
            public void done(List<UserInfo> list, BmobException e) {
                if (e == null){
                    Log.e("list",list+"");
                    Log.e("registerChecked","ok");
                    for (UserInfo a :
                            list) {
                        if (a.getAccount().equals(userPhone)) {
                            registerSuccess = false;
                            break;
                        }
                    }
                    if (!registerSuccess) {
                        ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.REGISTER_FAILED);
                    } else {
                        ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.REGISTER_SUCCESS);
                    }
                }else {
                    Log.e("registerChecked",e.getMessage());
                }

            }
        });
    }

    /**
     * 编辑个人信息页面需要用到的上传图片
     * @param bmobFile
     * @param userInfo
     */
    public void EditInfoUpLoadFile(final BmobFile bmobFile, final UserInfo userInfo){
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e==null){
                    Log.e("EditInfoUpLoadFile","ok");
                    userInfo.setHead(bmobFile);
                    MyApplication.getInstance().saveUserInfo(userInfo);
                    ((EditInfoActivity)context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                }else {
                    Log.e("EditInfoUpLoadFile",e.getMessage());
                    ((EditInfoActivity)context).handler.sendEmptyMessage(Constants.ResultCode.FAILED);
                }
            }
        });
    }

    /**
     * 更新用户信息----编辑个人信息页面
     * @param userInfo
     */
    public void EditInfpUpdateInfo(final UserInfo userInfo){
        userInfo.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e==null){
                    Log.e("EditInfpUpdateInfo","ok");
                    userInfo.setNewInfo(true);
                    MyApplication.getInstance().saveUserInfo(userInfo);
                    updateInfo(userInfo);
                    ((EditInfoActivity)context).handler.sendEmptyMessage(Constants.ResultCode.RESULT_SUCCESS);
                }else {
                    Log.e("EditInfpUpdateInfo",e.getMessage());
                }
            }
        });
    }

    /**
     * 更新用户信息
     * @param userInfo
     */
    public void updateInfo(UserInfo userInfo){
        userInfo.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e==null){
                    Log.e("updateInfo","ok");
                }else {
                    Log.e("updateInfo",e.getMessage());
                }
            }
        });
    }

    /**
     * 发布动态页面需要用到的上传图片
     * @param bmobFile
     */
    public void PublishUpLoadFile(final BmobFile bmobFile){
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e==null){
                    Log.e("PublishUpLoadFile","ok");
                    ((PublishActivity)context).friendCircle.setImg(bmobFile);
                    ((PublishActivity)context).isPic = true;
                    ImageLoaderUtils.initImage(context,
                            bmobFile.getFileUrl(),((PublishActivity)context).img, R.drawable.chat_xe_icon2_03);
                    ((PublishActivity)context).handler.sendEmptyMessage(Constants.ResultCode.UPLOAD_SUCCESS);
                }else {
                    Log.e("PublishUpLoadFile",e.getMessage());
                }
            }
        });
    }

    /**
     * 发布动态
     * @param friendCircle
     */
    public void publishFriendCircle(FriendCircle friendCircle){
        Log.e("publishFriendCircle","publishFriendCircle");
        friendCircle.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e==null){
                    Log.e("publishFriendCircle","ok");
                    ((PublishActivity)context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                }else {
                    Log.e("publishFriendCircle",e.getMessage());
                }
            }
        });

    }

    /**
     * 查询动态
     * @param resultCode
     * @param handler
     */
    public void queryFriendCircle(final int resultCode, final Handler handler){
        BmobQuery<FriendCircle> query = new BmobQuery<>();
        query.findObjects(new FindListener<FriendCircle>() {
            @Override
            public void done(List<FriendCircle> list, BmobException e) {
                if (e==null){
                    Log.e("queryFriendCircle","ok");
//                    for (int i = 0;i<list.size();i++){
//                        Log.e("list",list.get(i).getName());
//                    }
                    Collections.reverse(list);
                    ((MainActivity)context).friendCircleFragment.list.clear();
                    ((MainActivity)context).friendCircleFragment.list.addAll(list);
                    Message message = new Message();
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("list", (Serializable) list);
//                    message.setData(bundle);
                    message.what = resultCode;
                    handler.sendMessage(message);
                }else {
                    Log.e("queryFriendCircle",e.getMessage());
                }
            }
        });
    }

    /**
     * 编辑个人信息页面需要用到的上传图片
     * @param bmobFile
     * @param userInfo
     */
    public void ChangeInfoUpLoadFile(final BmobFile bmobFile, final UserInfo userInfo){
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e==null){
                    Log.e("ChangeInfoUpLoadFile","ok");
                    userInfo.setHead(bmobFile);
                    //MyApplication.getInstance().saveUserInfo(userInfo);
                    ((ChangeInfoActivity)context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                }else {
                    Log.e("ChangeInfoUpLoadFile",e.getMessage());
                    ((EditInfoActivity)context).handler.sendEmptyMessage(Constants.ResultCode.FAILED);
                }
            }
        });
    }

    /**
     * 更新用户信息----编辑个人信息页面
     * @param userInfo
     */
    public void ChangeUpdateInfo(final UserInfo userInfo){
//        Log.e("ChangeUpdateInfo","ChangeUpdateInfo");
        userInfo.update(userInfo.getId(),new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e==null){
                    Log.e("ChangeUpdateInfo","ok");
                    Log.e("sdf",userInfo.getName());
                    MyApplication.getInstance().saveUserInfo(userInfo);
                    ((ChangeInfoActivity)context).handler.sendEmptyMessage(Constants.ResultCode.RESULT_SUCCESS);
                }else {
                    Log.e("ChangeUpdateInfo",e.getMessage());
                }
            }
        });
    }

    /**
     * 查询动态--个人
     * @param resultCode
     * @param handler
     */
    public void queryPersonalCircle(final UserInfo userInfo, final int resultCode, final Handler handler){
        BmobQuery<FriendCircle> query = new BmobQuery<>();
        query.findObjects(new FindListener<FriendCircle>() {
            @Override
            public void done(List<FriendCircle> list, BmobException e) {
                if (e==null){
                    List<FriendCircle> friendCircles = new ArrayList<FriendCircle>();
                    for (FriendCircle f:list){
                        if (f.getId().equals(userInfo.getId())){
                            friendCircles.add(f);
                        }
                    }
                    Log.e("queryPersonalCircle","ok");
                    Collections.reverse(friendCircles);
                    Message message = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("list", (Serializable) friendCircles);
                    message.setData(bundle);
                    message.what = resultCode;
                    handler.sendMessage(message);
                }else {
                    Log.e("queryPersonalCircle",e.getMessage());
                }
            }
        });
    }

    /**
     * 查询个人相册
     * @param userInfo
     * @param resultCode
     * @param handler
     */
    public void queryPhoto(final UserInfo userInfo, final int resultCode, final Handler handler){
        BmobQuery<PhotoAlbum> query = new BmobQuery<>();
        query.findObjects(new FindListener<PhotoAlbum>() {
            @Override
            public void done(List<PhotoAlbum> list, BmobException e) {
                if (e==null){
                    Log.e("queryPhoto","ok");
                    for (PhotoAlbum photoAlbum : list){
                        if (photoAlbum.getId().equals(userInfo.getId())){
                            Message message = new Message();
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("list", photoAlbum);
                            message.setData(bundle);
                            message.what = resultCode;
                            handler.sendMessage(message);
                            break;
                        }
                    }

                  }else {
                    Log.e("queryPhoto",e.getMessage());
                }
            }
        });
    }
    public void getPhoto(final UserInfo userInfo, final int resultCode, final Handler handler){
        BmobQuery<PhotoAlbum> query = new BmobQuery<>();
        query.findObjects(new FindListener<PhotoAlbum>() {
            @Override
            public void done(List<PhotoAlbum> list, BmobException e) {
                if (e==null){
                    Log.e("queryPhoto","ok");
                    for (PhotoAlbum photoAlbum : list){
                        if (photoAlbum.getId().equals(userInfo.getId())){
//                            ((MainActivity)context).mineFragment.photoAlbum = photoAlbum;
                            handler.sendEmptyMessage(resultCode);
                            break;
                        }
                    }

                }else {
                    Log.e("queryPhoto",e.getMessage());
                }
            }
        });
    }
    /**
     * 上传图片
     * @param bmobFile
     * @param resultCode
     * @param handler
     */
    public void upLoadPic(final BmobFile bmobFile, final int resultCode, final Handler handler){
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e==null){
                    Log.e("upLoadPic","ok");
                    Message message = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("pic", bmobFile);
                    message.setData(bundle);
                    message.what = resultCode;
                    handler.sendMessage(message);
                }else {
                    Log.e("upLoadPic",e.getMessage());
                }
            }
        });
    }

    /**
     * 保存图集
     * @param photoAlbum
     * @param resultCode
     * @param handler
     */
    public void savePic(PhotoAlbum photoAlbum, final int resultCode, final Handler handler){
        photoAlbum.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if(e == null){
                    Log.e("savePic","ok");
                    handler.sendEmptyMessage(resultCode);
                }else {
                    Log.e("savePic",e.getMessage());
                }
            }
        });
    }

    /**
     * 更新图集
     * @param photoAlbum
     * @param resultCode
     * @param handler
     */
    public void updatePic(PhotoAlbum photoAlbum, final int resultCode, final Handler handler){
        photoAlbum.update(photoAlbum.getObjectId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if(e == null){
                    Log.e("updatePic","ok");
                    handler.sendEmptyMessage(resultCode);
                }else {
                    Log.e("updatePic",e.getMessage());
                }
            }
        });
    }

    public void findFriend(final String account, final int resultCode, final Handler handler){

        BmobQuery<UserInfo> query = new BmobQuery<>();
        query.findObjects(new FindListener<UserInfo>() {
            @Override
            public void done(List<UserInfo> list, BmobException e) {
                if(e == null){
                    Log.e("findFriend","ok");
                    for (UserInfo u:list){
                        if (account.equals(u.getAccount())){

                            cun = true;
                            userInfo = u;
                            break;
                        }
                    }

                }else {
                    Log.e("findFriend",e.getMessage());
                }

                if (cun){
                    Message message = new Message();
                    message.what = resultCode;
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("friend",userInfo);
                    message.setData(bundle);
                    handler.sendMessage(message);
                }else {
                    handler.sendEmptyMessage(404);
                }
            }

        });
    }

    /**
     * 保存新建的分组
     * @param friend
     * @param resultCode
     * @param handler
     */
    public void saveFenzu(final Friend friend, final int resultCode, final Handler handler){
        friend.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if(e == null){
                    Log.e("saveFenzu","ok");
                    Message message = new Message();
                    message.what = resultCode;
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("friend",friend);
                    message.setData(bundle);
                    handler.sendMessage(message);
                }else {
                    Log.e("saveFenzu",e.getMessage());
                }
            }
        });
    }

    /**
     * 更新好友列表
     * @param friend
     * @param resultCode
     * @param handler
     */
    public void updateFriend(final Friend friend, final int resultCode, final Handler handler){
        friend.update(friend.getId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if(e == null){
                    Log.e("updateFriend","ok");
                    handler.sendEmptyMessage(resultCode);
                }else {
                    Log.e("updateFriend",e.getMessage());
                }
            }
        });
    }

    /**
     * 查找好友列表
     * @param resultCode
     * @param handler
     */
    public void  queryFriendList(final UserInfo userInfo, final int resultCode, final Handler handler){
        BmobQuery<Friend> query = new BmobQuery<>();
        query.findObjects(new FindListener<Friend>() {
            @Override
            public void done(List<Friend> list, BmobException e) {
                if(e == null){
                    Log.e("updateFriend","ok");
                    List<Friend> friends = new ArrayList<Friend>();
                    for (Friend friend:list){
                        if (friend.getId().equals(userInfo.getId())){
                            friends.add(friend);
                        }
                    }
                    Message message = new Message();
                    message.what = resultCode;
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("friend", (Serializable) friends);
                    message.setData(bundle);
                    handler.sendMessage(message);
                }else {
                    Log.e("updateFriend",e.getMessage());
                }
            }
        });
    }

    /**
     * 查找朋友详细信息
     * @param resultCode
     * @param handler
     */
    public void findFriendInfo(final String id, final int resultCode, final Handler handler){
        BmobQuery<UserInfo> query = new BmobQuery<>();
        query.findObjects(new FindListener<UserInfo>() {
            @Override
            public void done(List<UserInfo> list, BmobException e) {
                if (e==null){
                    for (UserInfo userInfo:list){
                        if (userInfo.getAccount().equals(id)){
                            ((FriendHomePageActivity)context).userInfo = userInfo;
                            findFriendCircle(userInfo,resultCode,handler);
                            break;
                        }
                    }
                } else {

                }
            }
        });
    }

    /**
     * 查找朋友详细信息
     *
     * @param resultCode
     * @param handler
     */
    public void getFriendInfo(final String id, final int resultCode, final Handler handler) {
        BmobQuery<UserInfo> query = new BmobQuery<>();
        query.findObjects(new FindListener<UserInfo>() {
            @Override
            public void done(List<UserInfo> list, BmobException e) {
                if (e == null) {
                    for (UserInfo userInfo : list) {
                        if (userInfo.getAccount().equals(id)) {
                            Message message = new Message();
                            message.what = resultCode;
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("info", userInfo);
                            message.setData(bundle);
                            handler.sendMessage(message);
                            break;
                        }
                    }
                }else{

                }
            }
        });
    }

    /**
     * 查询朋友相册
     * @param userInfo
     * @param resultCode
     * @param handler
     */
    public void findFriendPhoto(final UserInfo userInfo, final int resultCode, final Handler handler){
        BmobQuery<PhotoAlbum> query = new BmobQuery<>();
        query.findObjects(new FindListener<PhotoAlbum>() {
            @Override
            public void done(List<PhotoAlbum> list, BmobException e) {
                if (e==null){
                    Log.e("queryPhoto","ok");
                    for (PhotoAlbum photoAlbum : list){
                        if (photoAlbum.getId().equals(userInfo.getId())){
                            Message message = new Message();
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("list", photoAlbum);
                            Log.e("queryPhoto",photoAlbum.getImg().size()+"");
                            message.setData(bundle);
                            message.what = resultCode;
                            handler.sendMessage(message);
                            break;
                        }
                    }

                }else {
                    Log.e("queryPhoto",e.getMessage());
                }
            }
        });
    }

    /**
     * 查询动态--朋友
     * @param resultCode
     * @param handler
     */
    public void findFriendCircle(final UserInfo userInfo, final int resultCode, final Handler handler){
        BmobQuery<FriendCircle> query = new BmobQuery<>();
        query.findObjects(new FindListener<FriendCircle>() {
            @Override
            public void done(List<FriendCircle> list, BmobException e) {
                if (e==null){
                    List<FriendCircle> friendCircles = new ArrayList<FriendCircle>();
                    for (FriendCircle f:list){
                        if (f.getId().equals(userInfo.getId())){
                            friendCircles.add(f);
                        }
                    }
                    Log.e("queryFriendCircle","ok");
                    Collections.reverse(friendCircles);
                    Message message = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("list", (Serializable) friendCircles);
                    message.setData(bundle);
                    message.what = resultCode;
                    handler.sendMessage(message);
                }else {
                    Log.e("queryFriendCircle",e.getMessage());
                }
            }
        });
    }
}
